<% layout('/layouts/default.html', {title: '生产领料管理', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(stProductMaterialFormBill.isNewRecord ? '新增生产领料' : '编辑生产领料')}
			</div>
			<div class="box-tools pull-right">
				<a href="#" class="btn btn-default" id="btn-src" ><i class="fa fa-filter"></i> ${text('加载工单')}
				</a>
				<% if (hasPermi('st:stProductMaterialFormBill:edit')){ %>
				<a href="#" class="btn btn-default" id="btn-approve" ><i class="fa fa-filter"></i> ${text('审核')}
				</a>
				<a href="#" class="btn btn-default" id="btn-revocation" ><i class="fa fa-filter"></i> ${text('弃审')}
				</a>
				<a href="#" class="btn btn-default" id="btn-save" ><i class="fa fa-filter"></i> ${text('保存')}
				</a>
				<% } %>
				<script>
					var aStatus=${stProductMaterialFormBill.approveState!"null"};
					approveBtnStatus(aStatus);
					function approveBtnStatus(status) {
						var $save=$("#btn-save");
						var $approve=$("#btn-approve");
						var $revocation=$("#btn-revocation");
						if (null == status ) {
							$save.show();
							$approve.hide();
							$revocation.hide();
						}
						if (2 == status) {
							$save.show();
							$approve.show();
							$revocation.hide();
						}
						if (4 == status) {
							$save.hide();
							$approve.hide();
							$revocation.show();
						}
					}
					function refresh(id) {
						location.replace("${ctx}/st/stProductMaterialFormBill/form?id="+id);
						// location.reload();
					}
					$("#btn-save").click(function () {
						$("#approveState").val(2);
						$("form").submit();
					});
					$("#btn-approve").click(function () {
						if(null == aStatus){
							js.showMessage("还没保存呢");
							return;
						}
						$("#approveState").val(4);
						$("form").submit();
					});
					$("#btn-revocation").click(function () {
						$("#approveState").val(2);
						$("form").submit();
					});
				</script>
				<div class="hide">
					<#form:listselect id="btn-src-0" title="生产工单选择"

					url="${ctx}/st/stProductBill/listSub?billStatus=2&approveState=4" allowClear="false"
					checkbox="false"  callbackFuncName="selectCallback"/>
				</div>
				<script>
					$("#btn-src").click(function () {
						// console.info("加载工单");
						$("#btn-src-0Button").click();
					});
				</script>
				<style>
					.my-del{
						/*display: none;*/
					}
				</style>
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${stProductMaterialFormBill}" action="${ctx}/st/stProductMaterialFormBill/save" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit">${text('基本信息')}</div>
				<#form:hidden path="id"/>
				<div class="row">
<!--					<div class="col-xs-6">-->
<!--						<div class="form-group">-->
<!--							<label class="control-label col-sm-4" title="">-->
<!--								<span class="required hide">*</span> ${text('单据号')}：<i class="fa icon-question hide"></i></label>-->
<!--							<div class="col-sm-8">-->
<!--								<#form:input path="billNo" maxlength="20" class="form-control"/>-->
<!--							</div>-->
<!--						</div>-->
<!--					</div>-->
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('单据日期')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="billDate" readonly="true" maxlength="20" class="form-control laydate"
									dataFormat="datetime" data-type="datetime" data-format="yyyy-MM-dd HH:mm"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('入账日期')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="tallyDate" readonly="true" maxlength="20" class="form-control laydate"
									dataFormat="datetime" data-type="datetime" data-format="yyyy-MM-dd HH:mm"/>
							</div>
						</div>
					</div>
<!--					<div class="col-xs-6">-->
<!--						<div class="form-group">-->
<!--							<label class="control-label col-sm-4" title="">-->
<!--								<span class="required hide">*</span> ${text('部门编码')}：<i class="fa icon-question hide"></i></label>-->
<!--							<div class="col-sm-8">-->
<!--								<#form:input path="deptCode" maxlength="20" class="form-control"/>-->
<!--							</div>-->
<!--						</div>-->
<!--					</div>-->
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('部门')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="deptName" maxlength="20" class="form-control"/>
							</div>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('扫码')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="barCode" maxlength="20" class="form-control"/>

							</div>
							<script>
								$('#barCode').bind('keydown', function(event) {
									var barCode = $("#barCode").val();
									var materialCode = barCode.split("_")[0];
									var batch_1 = barCode.split("_")[1];
									function openChoose(warehouseId,warehouseNumber) {
										var $closest = $("input[code=" + materialCode + "]").closest("tr");
										var toServer = $closest
												.find(".to-server")//my-use
												.val();
										var leftNumber = $closest.find(".left").val();
										js.layer.open({
											type: 2,
											area: ['400px', '500px'],
											title: '${text("导入用户数据")}',
											resize: false,
											scrollbar: true,
											content: "${ctx}/st/stProductMaterialFormBill/scanView?needNumber=" + toServer + "&warehouseNumber=" + warehouseNumber + "&left=" + leftNumber,
											success: function (layero, index) {
												layero.find('input[type="checkbox"]').iCheck();
											},
											btn: ['<i class="fa fa-check"></i> ${text("导入")}',
												'<i class="fa fa-remove"></i> ${text("关闭")}'],
											btn1: function (index, layero) {
												// var form = {
												// 	warehouseNumber: layero.find('#warehouseNumber').val(),
												// 	file: layero.find('#file').val()
												// };
												var win = layero.iframeWindow();
												var params = win.commit();
												var canClose = win.close();
												if(!canClose) return false;
												$closest.find(".get").val(params.getNumber);
												$closest.find(".case").val(params.caseNumber);

												var batch = $closest.find("[name=batchNumber]").data("batch");
												var batch_source = batch_1;
												if(!batch) batch=[];
												batch.push(warehouseId + "_" + batch_source + "_" + params.getNumber);
												$closest.find("[name=batchNumber]").data("batch", batch);
												var batch_value = batch.join(",");
												$closest.find("[name=batchNumber]").val(batch_value);

												// batch.push(batch_source+"_"+params.getNumber);
												var theory = $closest.find(".fake").val();
												var t = new BigNumber(params.getNumber).minus(new BigNumber(theory)).plus(new BigNumber(leftNumber)).toNumber();
												$closest.find(".my-use").val(t);
												// js.ajaxSubmitForm(form.inputForm, function(data){
												// 	js.showMessage(data.message);
												// 	if(data.result == Global.TRUE){
												// 		js.layer.closeAll();
												// 	}
												// 	page();
												// }, "json");
												return true;
											}
										});
									}

									if (event.keyCode == "13") {
										//回车执行查询
										// openChoose();
										js.layer.open({
											type: 2,
											area: ['400px', '500px'],
											title: '${text("选择仓位")}',
											resize: false,
											scrollbar: true,
											content: "${ctx}/st/stProductMaterialFormBill/scanView0?materialCode=" + materialCode + "&batchNumber=" + batch_1,
											success: function (layero, index) {
												layero.find('input[type="checkbox"]').iCheck();
											},
											btn: ['<i class="fa fa-check"></i> ${text("导入")}',
												'<i class="fa fa-remove"></i> ${text("关闭")}'],
											btn1: function (index, layero) {
												// var form = {
												// 	warehouseNumber: layero.find('#warehouseNumber').val(),
												// 	file: layero.find('#file').val()
												// };
												// console.info("index", index);
												// var frameId = $(layero).find("iframe").attr('id');
												// var iframeWin = window.frames[frameId]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
												// var iframeWin = window[layero.find('iframe')[0]['name']];
												var win = layero.iframeWindow();
												var params = win.commit();

												openChoose(params.warehouseId,params.number);
												// js.ajaxSubmitForm(form.inputForm, function(data){
												// 	js.showMessage(data.message);
												// 	if(data.result == Global.TRUE){
												// 		js.layer.closeAll();
												// 	}
												// 	page();
												// }, "json");
												return true;
											}
										});
										return false;
									}
								});
							</script>
						</div>
					</div>
					<div class="col-xs-6">
						<div class="form-group">
							<label class="control-label col-sm-4" title="">
								<span class="required hide">*</span> ${text('备注')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-8">
								<#form:input path="ramarks" maxlength="500" class="form-control"/>
								<#form:hidden path="approveState" />
<!--								单子id-->
								<#form:hidden path="productBillIds" />
							</div>
						</div>
					</div>
				</div>
				<script src="https://cdn.bootcdn.net/ajax/libs/bignumber.js/9.0.1/bignumber.js"></script>
				<h4 class="form-unit">${text('生产领料明细')}</h4>
				<div class="ml10 mr10">
					<table id="stProductMaterialFormBillDetailDataGrid"></table>
					<table id="batchDataGrid"></table>
					<% if (hasPermi('st:stProductMaterialFormBill:edit')){ %>
						<a href="#" id="stProductMaterialFormBillDetailDataGridAddRowBtn" class="btn btn-primary btn-sm mt10 mb10" style="display: none"><i class="fa fa-plus"></i> ${text('增行')}</a>
					<% } %>
					<script>
						function selectCallback(id, act, index, layero, selectData){
							$(".my-del").click();
							var idStr="";
							var allLength=0;
							for (var i = 0; i < selectData.length; i++) {
								let item = selectData[i];
								let billNumber=item.billNumber;//必须用 let
								$.ajax({
									url:"${ctx}/st/formula/stFormulaName/detail",
									dataType:'json',
									type:'POST',
									data:{
										//请求参数
										id: item.thisFormula,
										// formulaId:formula/stFormulaName
									},
									success:function(result){
										// console.info(result);
										for (var i = 0; i < result.list.length; i++) {
											var it = result.list[i];
											// if(-1 == it.percent) continue;
											var $materialName = $("[code="+it.materialRecord.materialCode+"]");
											var materialName=null;
											if($materialName.size()==0){
												$("#stProductMaterialFormBillDetailDataGridAddRowBtn").click();
												materialName = $(($(($("#stProductMaterialFormBillDetailDataGrid").find("tr"))[allLength+ 1]).find('td'))[3]);
                                                allLength++;
											}else{
                                                materialName = $materialName;
                                            }


											materialName.find(".form-control").val(it.materialName).trigger('change');
											materialName.find("input.name:hidden").val(it.materialName).attr("code",it.materialRecord.materialCode);
											// materialName.find("input.code:hidden").val(it.materialRecord.materialCode);
											var unit = materialName.next();
											unit.find(".form-control").val('KG');//todo 不能写死
											var theoryNumber = unit.next();
											var n1 = new BigNumber(it.percentIn);
											var n2 = new BigNumber(billNumber);
											// if(i==0) console.info(billNumber);
											var res = n1.times(n2).div(100);
											var prime = theoryNumber.find(".form-control").val();
											if(""==prime) prime = 0;
											var r2 = new BigNumber(res).plus(prime);
											// console.info("prime", prime);
											// console.info("res",r2.toNumber());
											theoryNumber.find(".form-control").val(r2);

											var getNumber = theoryNumber.next();
											getNumber.find(".form-control").val(0);

											var caseNumber = getNumber.next();
											caseNumber.find(".form-control").val(0);
											var approve=0;
											if(it.materialRecord.smallMaterialApprove){
												if(3==it.materialRecord.smallMaterialApprove.takeStatus){
													approve=it.materialRecord.smallMaterialApprove.onlineNumber;
												}else if(1==it.materialRecord.smallMaterialApprove.takeStatus){
													approve=it.materialRecord.smallMaterialApprove.theoryLeftNumber;
												}else{//2 这种状态是不是就极端化了
													js.showMessage("关闭本页，进行小料间审核");
													$(".my-del").click();
													break;
												}
											}
											//小料间余量
											var smallMaterialLeft = caseNumber.next();
											smallMaterialLeft.find(".form-control").val(approve);

											//理论剩余量
											var theoryLeft = smallMaterialLeft.next();
											theoryLeft.find(".form-control").val(new BigNumber(approve).minus(new BigNumber(r2)).toNumber());

											var materialType = theoryLeft.next();
											materialType.find(".form-control").val(it.materialRecord.materialCategory).trigger('change');
											materialType.find("input:hidden").val(it.materialRecord.materialCategory);

                                            var primaryId = materialType.next();
                                            var $inputPrimary = primaryId.find(".form-control");
                                            var ids = $inputPrimary.data("id");
                                            if(!ids){
                                                ids = [];
                                            }
                                            ids.push(item.id);
                                            $inputPrimary.data("id",ids);
                                            $inputPrimary.val(ids.join(","));
										}
									}
								});
								idStr += item.id + ",";
							}
							$("#productBillIds").val(idStr);
						}
					</script>
				</div>
			</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
<!--						<% if (hasPermi('st:stProductMaterialFormBill:edit')){ %>-->
<!--							<button type="submit" class="btn btn-sm btn-primary" id="btnSubmit"><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;-->
<!--						<% } %>-->
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<script>
	$(function () {
		$("#stProductMaterialFormBillDetailDataGrid").on("click",".show-batch",function () {
			var batch = $(this).closest("tr").find("[name=batchNumber]").val();
			var bArr = batch.split(",");
			var tableList=[];
			for (var i = 0; i < bArr.length; i++) {
				var item0 = bArr[i];
				var item={
					id:i+1,
					batch:item0.split("_")[1],
					number:item0.split("_")[2],
				}
				tableList.push(item);
			}
			$('#batchDataGrid').dataGrid('setParam', {
				data:tableList,
				page: 1, rowNum: 5000
			}, true).dataGrid('reloadGrid');
		});
	})

	$('#batchDataGrid').dataGrid({
		// searchForm: $("#searchForm"),
		data:[],
		datatype: "local",
		columnModel: [
			{header: '主键', name: 'id', editable: true, hidden: true},
			{header: '${text("批号")}', name: 'batch', index: 'a.tally_date', width: 150, align: "center"},
			{header: '${text("数量")}', name: 'number', index: 'a.dept_code', width: 150, align: "left"},
		],
		// 加载成功后执行事件
		ajaxSuccess: function (data) {

		}
	});
//初始化生产领料明细DataGrid对象
$("#stProductMaterialFormBillDetailDataGrid").dataGrid({

	data: ${toJson(stProductMaterialFormBill.stProductMaterialFormBillDetailList)},
	datatype: "local", // 设置本地数据
	autoGridHeight: function(){return 'auto'}, // 设置自动高度

	// 设置数据表格列
	columnModel: [
		{header:'状态', name:'status', editable:true, hidden:true},
		{header:'主键', name:'id', editable:true, hidden:true},
		{header:'${text("物料名称")}', name:'materialName', width:150,
			editable:true, edittype:'select', editoptions:{'class':'form-control',
				items: $.merge([{materialName:'&nbsp;',id:''}], ${materialRecordList}),
				itemLabel: 'materialName', itemValue: 'id', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
					element.name="ignore_materialName";
					$(element).attr("disabled",true);
					$(element).after("<input name='materialName' class='name' code='' value='"+element.value+"' hidden>");
				}
			}
		},
		{header:'${text("单位")}', name:'unit', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'36', 'class':'form-control' ,'readonly':true}},
		{header:'${text("理论用量")}', name:'theoryNumber', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number fake to-server','readonly':true}},
		{header:'${text("领料数量")}', name:'getNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'8', 'class':'form-control  get','readonly':true}},
		{header:'${text("件数")}', name:'caseNumber', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'8', 'class':'form-control number case','readonly':true}},
		{header:'${text("小料间余量")}', name:'smallMaterialLeft', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number left','readonly':true}},
		{header:'${text("理论剩余值")}', name:'theoryLeft', width:150, editable:true, edittype:'text', editoptions:{'class':'form-control number my-use','readonly':true}},
		{header:'${text("原料类型")}', name:'materialType', width:100,
			editable:true, edittype:'select', editoptions:{'class':'form-control digits',
				items: $.merge([{dictLabel:'&nbsp;',dictValue:''}], ${@DictUtils.getDictListJson('st_material_category')}),
				itemLabel: 'dictLabel', itemValue: 'dictValue', dataInit: function(element){
					$(element).select2().on("change",function(){$(this).resetValid()});
					element.name="ignore_materialType";
					$(element).attr("disabled",true);
					$(element).after("<input name='materialType' value='"+element.value+"' hidden>");
				}
			}
		},
		{header:'${text("父 id")}', name:'primaryId', editable:true, hidden:true},
		{header:'${text("父 id")}', name:'parentId.id', editable:true, hidden:true},
		{header:'${text("批号")}', name:'batchNumber', width:150, editable:true, edittype:'text', editoptions:{ 'class':'form-control'},hidden:true},
		{header:'${text("操作")}', name:'actions', width:80, sortable:false, fixed:true, formatter: function(val, obj, row, act){
			var actions = [];
				if (val == 'new'){
					// actions.push('<a href="#"  class="detail-del" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#stProductMaterialFormBillDetailDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
					actions.push('<a href="#" class="my-del" onclick="$(\'#stProductMaterialFormBillDetailDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\');return false;"></a>&nbsp;');
					actions.push('<a href="#" class="show-batch" ><i class="fa fa-bars"></i></a>&nbsp;');
				}else{
					// actions.push('<a href="#" class="detail-del" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#stProductMaterialFormBillDetailDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
					actions.push('<a href="#" class="my-del" onclick="$(\'#stProductMaterialFormBillDetailDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');return false;"></a>&nbsp;');
					actions.push('<a href="#" class="show-batch" ><i class="fa fa-bars"></i></a>&nbsp;');
				}
			return actions.join('');
		}, editoptions: {defaultValue: 'new'}}
	],

	// 编辑表格参数
	editGrid: true,				// 是否是编辑表格
	editGridInitRowNum: 1,		// 编辑表格的初始化新增行数
	editGridAddRowBtn: $('#stProductMaterialFormBillDetailDataGridAddRowBtn'),	// 子表增行按钮
	editGridAddRowInitData: {id: '', status: Global.STATUS_NORMAL},	// 新增行的时候初始化的数据

	// 编辑表格的提交数据参数
	editGridInputFormListName: 'stProductMaterialFormBillDetailList', // 提交的数据列表名
	editGridInputFormListAttrs: 'status,id,materialName,unit,theoryNumber,getNumber,caseNumber,smallMaterialLeft,theoryLeft,materialType,parentId.id,batchNumber,', // 提交数据列表的属性字段

	// 加载成功后执行事件
	ajaxSuccess: function(data){

	}
});
</script>
<script>
	$("#inputForm").validate({
		submitHandler: function(form){
			js.ajaxSubmitForm($(form), function(data){
				var id = data.data.id;
				// $("#id").val(data.data.id);
				// approveBtnStatus(data.data.approveState);
				refresh(id);
				js.showMessage(data.message);
				// if(data.result == Global.TRUE){
				// 	js.closeCurrentTabPage(function(contentWindow){
				// 		contentWindow.page();
				// 	});
				// }
			}, "json");
		}
	});
</script>